package com.gzc.house.user.service;

import com.google.common.collect.ImmutableMap;
import com.gzc.house.user.common.UserException;
import com.gzc.house.user.common.UserException.Type;
import com.gzc.house.user.dao.UserMapper;
import com.gzc.house.user.model.User;
import com.gzc.house.user.utils.HashUtils;
import com.gzc.house.user.utils.JwtHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public User getUserById(Long id) {

        return userMapper.selectByPrimaryKey(id);
    }

    public User auth(String email, String passwd) {
        if (StringUtils.isBlank(email) || StringUtils.isBlank(passwd)) {
            throw new UserException(Type.USER_AUTH_FAIL, "User Auth Fail");
        }
        User user = new User();
        user.setEmail(email);
        user.setPasswd(HashUtils.encryPassword(passwd));
        user.setEnable(true);
        List<User> list =  getUserByQuery(user);
        if (!list.isEmpty()) {
            User retUser = list.get(0);
            onLogin(retUser);
            return retUser;
        }
        throw new UserException(Type.USER_AUTH_FAIL,"User Auth Fail");
    }

    private List<User> getUserByQuery(User user) {
        // TODO
        return null;
    }

    private void onLogin(User user) {
        String token = JwtHelper.genToken(ImmutableMap.of("email", user.getEmail(), "name", user.getName(), "ts", Instant.now().getEpochSecond() + ""));
        renewToken(token, user.getEmail());
        user.setToken(token);
    }

    private String renewToken(String token, String email) {
       // redisTemplate.opsForValue().set(email, token);
       // redisTemplate.expire(email, 30, TimeUnit.MINUTES);
        return token;
    }
}
